package com.jdcjk.project.setting.view;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.jdcjk.Constant;
import com.jdcjk.R;
import com.jdcjk.UrlAddress;
import com.jdcjk.base.presenter.BasePresenter;
import com.jdcjk.base.view.BaseActivity;
import com.jdcjk.chat.OpenFireConnectionManager;
import com.jdcjk.project.account.model.entity.AddressInfo;
import com.jdcjk.project.account.model.entity.Result;
import com.jdcjk.project.account.view.AddressPopupWindow;
import com.jdcjk.project.login.view.LoginActivity;
import com.jdcjk.project.setting.presenter.SettingPresenter;
import com.jdcjk.util.PreferencesUtils;
import com.jdcjk.util.dtr.zxing.AddressInfoUtis;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Administrator on 2016/12/28 0028.
 */

public class UserInfoActivity extends BaseActivity<SettingPresenter> implements View.OnClickListener {
    private final String TAG = UserInfoActivity.class.getSimpleName();
    //用户账号textview
    private TextView userAccount_textView;
    //用户姓名editText
    private EditText userName_editText;
    //用户手机号textview
    private TextView userPhone_textView;
    //用户邮箱editText
    private EditText userEmail_editText;
    //用户地址textview
    private TextView userAddress_textview;
    //返回button
    private ImageButton back_button;
    //顶栏标题textview
    private TextView barTitle_textview;
    //退出button
    private Button userInfoExit_button;
    //修改信息button
    private Button userInfoUpdata_button;

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    public void initContentView(Bundle savedInstanceState) {
        barTitle_textview = (TextView) findViewById(R.id.bar_title_textview);
        barTitle_textview.setText(R.string.my_account);
        back_button = (ImageButton) findViewById(R.id.back_btn);
        back_button.setOnClickListener(this);
        //设置用户信息
        userAccount_textView = (TextView) findViewById(R.id.user_account_tv);
        userName_editText = (EditText) findViewById(R.id.user_name_et);
        userPhone_textView = (TextView) findViewById(R.id.user_phone_tv);
        userEmail_editText = (EditText) findViewById(R.id.user_email_et);
        userAddress_textview = (TextView) findViewById(R.id.user_address_tv);
        String userAccount = PreferencesUtils.getString(this, Constant.UserInfo.account);
        String username = PreferencesUtils.getString(this, Constant.UserInfo.username);
        String phone = PreferencesUtils.getString(this, Constant.UserInfo.phone);
        String email = PreferencesUtils.getString(this, Constant.UserInfo.email);
        String address = PreferencesUtils.getString(this, Constant.UserInfo.address);
        userAccount_textView.setText(userAccount);
        userName_editText.setText(username);
        userPhone_textView.setText(userAccount);
        userEmail_editText.setText(email);
        if (address != null && !address.equals("")) {
            userAddress_textview.setText(address);
        }
        userAddress_textview.setOnClickListener(this);
        //退出按钮
        userInfoExit_button = (Button) findViewById(R.id.user_info_exit_btn);
        userInfoExit_button.setOnClickListener(this);
        //修改信息按钮
        userInfoUpdata_button = (Button) findViewById(R.id.user_info_updata_btn);
        userInfoUpdata_button.setOnClickListener(this);

    }

    @Override
    public SettingPresenter bindPresenter() {
        presenter = new SettingPresenter(getBaseContext());
        return presenter;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                //返回按钮
                finish();
                break;
            case R.id.user_info_exit_btn:
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                finish();
                //删除对应的登录用户信息
                PreferencesUtils.deleteUserInfo(this);
                //断开openfire连接
                OpenFireConnectionManager.getInstance().disconnect();
                break;
            case R.id.user_address_tv:
                //弹出地址选择dialog
                choiceAddress();
                break;
            case R.id.user_info_updata_btn:
                String account = PreferencesUtils.getString(this, Constant.UserInfo.account);
                final String username = userName_editText.getText().toString();
                final String email = userEmail_editText.getText().toString();
                final String address = userAddress_textview.getText().toString();
                //修改用户信息
                presenter.updateUserInfo(UrlAddress.UPDATA_USER_INFO, account, username, email, address, new BasePresenter.OnUIThreadListener<Result>() {
                    @Override
                    public void onBefore(Request request, int id) {

                    }

                    @Override
                    public void onAfter(int id) {

                    }

                    @Override
                    public void onError(Call call, Exception e, int i) {
                        Toast.makeText(UserInfoActivity.this, R.string.toast_updata_fail, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Result result) {
                        switch (result.getStatus()) {
                            case "OK":
                                Toast.makeText(UserInfoActivity.this, R.string.toast_updata_success, Toast.LENGTH_SHORT).show();
                                PreferencesUtils.setString(UserInfoActivity.this, Constant.UserInfo.username, username);
                                PreferencesUtils.setString(UserInfoActivity.this, Constant.UserInfo.email, email);
                                PreferencesUtils.setString(UserInfoActivity.this, Constant.UserInfo.address, address);
                                finish();
                                break;
                            case "FAILED":
                                Toast.makeText(UserInfoActivity.this, R.string.toast_updata_fail, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                break;
        }
    }

    /**
     * *********************************************设置地址*********************************************
     */

    private AddressPopupWindow addressPopupWindow;
    private String provinceName;
    private String cityName;
    private String areaName;
    private ArrayList<AddressInfo> addressInfoList;
    //地址类型
    private AddressInfoUtis.AddressType addressType;

    public void choiceAddress() {
        addressInfoList = AddressInfoUtis.getProvinceInfo(this);
        addressType = AddressInfoUtis.AddressType.getFromString(AddressInfoUtis.AddressType.PROVINCE.toString());
        showAddressPopuwindow(addressType, addressInfoList);
    }

    /**
     * 弹出地址选择器
     *
     * @param addressType  地址类型
     * @param addressInfos 区域信息列表
     */
    private void showAddressPopuwindow(AddressInfoUtis.AddressType addressType, ArrayList<AddressInfo> addressInfos) {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = 0.5f;
        UserInfoActivity.this.getWindow().setAttributes(lp);//改变背景颜色
        addressPopupWindow = new AddressPopupWindow(UserInfoActivity.this, addressType, itemsOnClick, addressInfos);
        addressPopupWindow.showAtLocation(UserInfoActivity.this.findViewById(R.id.activity_user_info), Gravity.CENTER, 0, 0);
        addressPopupWindow.update();
        addressPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = UserInfoActivity.this.getWindow().getAttributes();
                lp.alpha = 1f;//恢复背景颜色
                UserInfoActivity.this.getWindow().setAttributes(lp);
            }
        });
    }

    // PopupWindow弹出窗体的实现监听类
    private AdapterView.OnItemClickListener itemsOnClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (addressType == AddressInfoUtis.AddressType.PROVINCE) {
                String provinceCode = ((AddressInfo) parent.getItemAtPosition(position)).getProvinceCode();
                provinceName = ((AddressInfo) parent.getItemAtPosition(position)).getName();
                addressPopupWindow.dismiss();
                addressInfoList = AddressInfoUtis.getCityInfo(UserInfoActivity.this, provinceCode);
                addressType = AddressInfoUtis.AddressType.getFromString(AddressInfoUtis.AddressType.CITY.toString());
                showAddressPopuwindow(addressType, addressInfoList);
            } else if (addressType == AddressInfoUtis.AddressType.CITY) {
                String cityCode = ((AddressInfo) parent.getItemAtPosition(position)).getProvinceCode();
                cityName = ((AddressInfo) parent.getItemAtPosition(position)).getName();
                addressPopupWindow.dismiss();
                addressInfoList = AddressInfoUtis.getAreaInfo(UserInfoActivity.this, cityCode);
                addressType = AddressInfoUtis.AddressType.getFromString(AddressInfoUtis.AddressType.AREA.toString());
                showAddressPopuwindow(addressType, addressInfoList);
            } else if (addressType == AddressInfoUtis.AddressType.AREA) {
                areaName = ((AddressInfo) parent.getItemAtPosition(position)).getName();
                addressPopupWindow.dismiss();
                userAddress_textview.setTextColor(getResources().getColor(R.color.black));
                if (provinceName.equals(cityName) && !cityName.equals(areaName)) {
                    userAddress_textview.setText(cityName + "-" + areaName);
                } else if (!provinceName.equals(cityName) && cityName.equals(areaName)) {
                    userAddress_textview.setText(provinceName + "-" + cityName);
                } else if (provinceName.equals(cityName) && cityName.equals(areaName)) {
                    userAddress_textview.setText(areaName);
                } else {
                    userAddress_textview.setText(provinceName + "-" + cityName + "-" + areaName);
                }
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        refreshView();
    }


}
